package com.tcs.test.executor.test;

import com.tcs.test.BaseJunit4Test;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * wait and sleep 的区别
 */
public class WaitAndSleepOfThread {

    public static final Logger logger = LoggerFactory.getLogger(WaitAndSleepOfThread.class);

    private Object obj = new Object();

    @Test
    public void main() {
        Runab run1 = new Runab("t1");
        Runab run2 = new Runab("t2");
        Thread t1 = new Thread(run1 , "t1");
        Thread t2 = new Thread(run2 , "t2");
        t1.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            logger.error("" , e);
        }
        t2.start();
//        for (int i = 1; i <= 1000; i++) {
//            Runab run = new Runab("t" + i);
//            Thread t = new Thread(run , "t" + i);
//            t.start();
//        }
        try {
            Thread.sleep(200000);
        } catch (InterruptedException e) {
            logger.error("" , e);
        }
    }

    class Runab implements Runnable {

        private String name;

        public Runab(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            lock(name);
        }
    }

    public void lock(String name) {
        logger.info(" 线程: {} " , name);
//        if (name.equals("t1")) {
            logger.info(" 线程: {} 休眠" , name);
            try {
                synchronized (obj) {
                    logger.info(" 线程: {} wait" , name);
//                    obj.wait();
                    Thread.sleep(5 * 1000L);
//                    obj.wait();
                    logger.info(" 线程: {} wait -- eixt" , name);
                }
            } catch (InterruptedException e) {
                logger.error("" , e);
            }
//        }
        logger.info(" 线程: {} exit" , name);
    }
}
